<?php

// +----------------------------------------------------------------------
// |Author: 翼小菜
// +----------------------------------------------------------------------
// |Description: cveAdmin 验证码用
// +----------------------------------------------------------------------
// |更多功能可联系QQ314688769
// +----------------------------------------------------------------------
namespace api\cveadmin\controller;
use cmf\controller\RestBaseController;
use Fastknife\Exception\ParamException;
use Fastknife\Service\ClickWordCaptchaService;
use Fastknife\Service\BlockPuzzleCaptchaService;

class CaptchaController extends RestBaseController
{
    /** 
     * @description: 获取验证码
     * @return {*}
     */    
    public function index()
    {
        $type = $this->request->param('captcha_type', 'blockPuzzle');
        try {
            $service = $this->getCaptchaService($type);
            $data = $service->get();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
       /*  如果开发框架开启了debug、trace，导致前端项目无法正确获取到后台接口的返回数据，可以修改为本注释内的接口返回方式*/
        $response = [
            'error' => false,
            'repCode' => '0000',
            'repData' => $data,
            'repMsg' => null,
            'success' => true,
        ];
        return json($response);

        //$this->success('success',$data);
    }

    /** 
     * @description: 校验行为
     * @return {*}
     */    
    public function check()
    {
        $data = request()->post();
        $captchaType = $data['captcha_type'];
        try {
            $service = $this->getCaptchaService($captchaType);
            $service->check($data['token'], $data['pointJson']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        /*  如果开发框架开启了debug、trace，导致前端项目无法正确获取到后台接口的返回数据，可以修改为本注释内的接口返回方式*/
        $response = [
            'error' => false,
            'repCode' => '0000',
            'repData' => [],
            'repMsg' => null,
            'success' => true,
        ];
        return json($response);
       // $this->success('success');
    }

    protected function getCaptchaService($captchaType = 'blockPuzzle')
    {
        $config = config('captcha');
        switch ($captchaType) {
            case "clickWord":
                $service = new ClickWordCaptchaService($config);
                break;
            case "blockPuzzle":
                $service = new BlockPuzzleCaptchaService($config);
                break;
            default:
                throw new ParamException('captchaType参数不正确！');
        }
        return $service;
    }

    
}
